package com.xm.transfer.dao.impl;

import com.xm.transfer.annotations.Autowired;
import com.xm.transfer.annotations.Component;
import com.xm.transfer.dao.AccountDao;
import com.xm.transfer.pojo.Account;
import com.xm.transfer.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Component
public class JDBCAccountDaoImpl implements AccountDao {

    @Autowired
    private ConnectionUtils connectionUtils;

    @Override
    public Account selectAccountByCardNo(String cardNo) throws Exception {
        Connection con = connectionUtils.getCurrentThreadConnection();
        String sql = "select * from account where account = ?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1, cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();
        Account account = new Account();
        while (resultSet.next()) {
            account.setId(resultSet.getInt("id"));
            account.setName(resultSet.getString("name"));
            account.setAccount(resultSet.getString("account"));
            account.setAmount(resultSet.getDouble("amount"));
        }
        resultSet.close();
        preparedStatement.close();
        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws Exception {
//        DruidPooledConnection con = DruidUtils.getInstance().getConnection();
        Connection con = connectionUtils.getCurrentThreadConnection();
        String sql = "update account set amount = ? where account = ?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setDouble(1, account.getAmount());
        preparedStatement.setString(2, account.getAccount());
        int num = preparedStatement.executeUpdate();
        preparedStatement.close();
//        con.close();
        return num;
    }
}
